package com.cloudmusic.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cloudmusic.constant.Const;
import com.cloudmusic.entity.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cloudmusic.service.CustomListService;

@Controller
@RequestMapping("music/customlist")
public class CustomListController {

	@Autowired
	CustomListService customListService;

	private Logger log=Logger.getLogger(this.getClass());

	/**
	*
	*
	*
	* */
	@RequestMapping("addcustomlist")
	@ResponseBody
	public JSONObject addCustomList(HttpSession session,String listname) {
		JSONObject json = new JSONObject();
		String userId = ((User)session.getAttribute(Const.SESSION_KEY)).getUid();
		log.info(userId);
		int i = customListService.checkCustomListName(userId,listname);
		if(i == 0){
			String lid = UUID.randomUUID().toString();
			try{
				customListService.addCustomList(lid, listname, userId);
				log.info("添加自定义歌单成功");
				json.put("result","success");
				json.put("listname",listname);
                json.put("lid",lid);
			}catch (Exception e){
				log.error("error:",e);
				json.put("result","error");
			}
		}else{
			log.info("已有相同名字歌单");
			json.put("result","false");
		}
		return json;
	}
	
	@RequestMapping("deletecustomlist")
	@ResponseBody
	public JSONObject deleteCustomList(String lid) {
		JSONObject json = new JSONObject();
		try{
			customListService.deleteCustomList(lid);
			log.info("删除自定义歌单成功");
			json.put("result","success");
		}catch (Exception e){
			log.error("error:",e);
			json.put("result","error");
		}
		return json;
	}
	
	@RequestMapping("updatelistname")
	@ResponseBody
	public JSONObject updateListname(HttpServletRequest request, String lid, String newlistname) {
		JSONObject json = new JSONObject();
		String userId = ((User)request.getSession().getAttribute(Const.SESSION_KEY)).getUid();
		int i = customListService.checkCustomListName(userId,newlistname);
		if(i == 0){
			try{
				customListService.updateCustomListName(lid, newlistname);
				log.info("修改自定义歌单名称成功");
				json.put("result","success");
			}catch (Exception e){
				log.error("error:",e);
				json.put("result","error");
			}
		}else{
			log.info("已有相同名字歌单");
			json.put("result",false);
		}
		return json;
	}
	
	@RequestMapping("selectcustomlistmusic")
	@ResponseBody
	public JSONObject selectCustomListMusic(HttpSession session,String lid) {
		String userId = ((User)session.getAttribute(Const.SESSION_KEY)).getUid();
		JSONObject json = customListService.selectCustomListMusic(lid,userId);
		return json;
	}
	
	
}
